<?php

require_once(APPPATH.'controllers/epicentr.php');

class Jobs extends Epicentr {

	private $uploadpath = '../epicentr_files/';
	private $allowed_file_types = 'gif|jpg|png|doc|pdf|xls|ppt|pps';

	public function Jobs() {
		parent::Epicentr();
		
		switch ($this->authentication->getProfileType()) {
			case 'admin':
				$this->permissions->editjob = true;
				$this->permissions->createinvoice = true;
				$this->permissions->assignusers = true;
				$this->permissions->showtime = true;
				$this->permissions->deleteupdates = true;
				$this->permissions->showdepartments = true;
				$this->permissions->adddepartments = true;
				$this->permissions->editdepartments = true;
				$this->permissions->addtasks = true;
				$this->permissions->edittasks = true;
				$this->permissions->addcosts = true;
				$this->permissions->editcosts = true;
				$this->permissions->changejobstatus = true;
				$this->permissions->editfiles = true;
			break;
			case 'standard';
				$this->permissions->editjob = false;
				$this->permissions->createinvoice = false;
				$this->permissions->assignusers = false;
				$this->permissions->showtime = true;
				$this->permissions->deleteupdates = false;
				$this->permissions->showdepartments = true;
				$this->permissions->adddepartments = true;
				$this->permissions->editdepartments = true;
				$this->permissions->addtasks = true;
				$this->permissions->edittasks = true;
				$this->permissions->addcosts = true;
				$this->permissions->editcosts = true;
				$this->permissions->changejobstatus = false;
				$this->permissions->editfiles = true;
			break;
			default:
				$this->permissions->editjob = false;
				$this->permissions->createinvoice = false;
				$this->permissions->assignusers = false;
				$this->permissions->showtime = false;
				$this->permissions->deleteupdates = false;
				$this->permissions->showdepartments = true;
				$this->permissions->adddepartments = false;
				$this->permissions->editdepartments = false;
				$this->permissions->addtasks = false;
				$this->permissions->edittasks = false;
				$this->permissions->addcosts = false;
				$this->permissions->editcosts = false;
				$this->permissions->changejobstatus = false;
				$this->permissions->editfiles = false;
			break;
		}
		
	}
	
	public function index() {
		redirect('epicentr/projects', 'location');		
    }
    
    private function canAccess($jobid) {
    	
    	if ($this->authentication->getProfileType() == 'client') {
			$this->load->model('contactmodel');
			$this->load->model('jobsmodel');
			
			$contact = $this->contactmodel->retrieve_by_field('email1', $this->authentication->getUserEmailaddress() );
			$mycompany = $this->contactmodel->getCurrentCompany($contact->id);
			
			$job = $this->jobsmodel->retrieve_by_pkey($jobid);
			
			if ($mycompany->id == $job->companyid) return true;
			else return false;
			
		} else return true;
    	
    }
    
		public function milestones($jobid, $company_name = false) {
			$this->load->model('jobsmodel');
	    	$this->load->model('companiesmodel');
	    	$this->load->model('costcentermodel');
	    	$this->load->model('deadlinemodel');
	    	$this->load->model('timesheetmodel');

			$job = $this->jobsmodel->retrieve_by_name($jobid, $company_name);
			if (!$job && intval($jobid)) $job = $this->jobsmodel->retrieve_by_pkey($jobid);

	    	if (!$this->canAccess($jobid)) redirect('');
   	
	    	$this->view_data['page_js'][] = 'job';

	    	$jobid = $job->id;
	    	$company = $this->companiesmodel->retrieve_by_pkey($job->companyid);

	    	$this->view_data['job'] = $job;
			$this->view_data['company'] = $company;

			$activities = $this->costcentermodel->getActivitiesForJob($jobid);
			$this->view_data['activities'] = $activities;

			$this->view_data['completion'] = $this->jobsmodel->getCompletion($jobid);

			//get departments
	    	$costcenters = $this->costcentermodel->getCostCentersForJob($job->id);
			//get time logged for departments
			if ($costcenters) {
				foreach($costcenters as $key => $department) {
					$costcenters[$key]->timespent = $this->timesheetmodel->getTimeSpent($job->id, $department->id);
				}
			}
			$this->view_data['costcenters'] = $costcenters;

			$this->calcJobTime($job->id);

			if ($company->client) $this->view_data['maintab'] = 'Clients';
			else if ($company->prospect) $this->view_data['maintab'] = 'Prospects';
			else if ($company->supplier) $this->view_data['maintab'] = 'Suppliers';
			
			$this->layout->buildPage('jobs/milestones', $this->view_data);
		}

		public function costs($jobid, $company_name = false) {
			$this->load->model('jobsmodel');
	    	$this->load->model('companiesmodel');
	    	$this->load->model('costmodel');

			$job = $this->jobsmodel->retrieve_by_name($jobid, $company_name);
			if (!$job && intval($jobid)) $job = $this->jobsmodel->retrieve_by_pkey($jobid);

	    	if (!$this->canAccess($jobid)) redirect('');
 	
	    	$this->view_data['page_js'][] = 'job';

	    	$jobid = $job->id;
	    	$company = $this->companiesmodel->retrieve_by_pkey($job->companyid);

	    	$this->view_data['job'] = $job;
			$this->view_data['company'] = $company;

	    	$costs = $this->costmodel->getCostsFor( $job->id );
	    	$this->view_data['costs'] = $costs;

	    	$suppliers = $this->companiesmodel->find( array('archived' => 0, 'supplier' => 1), null, null, 'company_name');

	    	$this->view_data['suppliers'] = $suppliers;

			$this->calcJobTime($job->id);

			if ($company->client) $this->view_data['maintab'] = 'Clients';
			else if ($company->prospect) $this->view_data['maintab'] = 'Prospects';
			else if ($company->supplier) $this->view_data['maintab'] = 'Suppliers';
			
			$this->layout->buildPage('jobs/costs', $this->view_data);
		}



    public function add($companyid = 0) {
    	$this->load->model('basemodel');
    	$this->load->model('jobsmodel');
    	$this->load->model('companiesmodel');
    	
    	$submit = $this->input->post('submit', false);
    	
    	if ($submit) {
    		$job = $this->_get_job_values('add');
    		$job->companyid = $this->input->post('companyid');
    		
    		$jobid = $this->jobsmodel->add($job);
  
  			$this->db_session->set_flashdata('flashmessage', 'The new '.$job->job_status.' job - '.$job->job_title.' was added.');
  
    		redirect('jobs/view/'.$jobid, 'location');
    	} else {
	    	$this->view_data['page_js'][] = 'jobs_costcenter';
    		
    		$this->view_data['company'] = $this->companiesmodel->retrieve_by_pkey($companyid);
    		
    		$this->basemodel->setModel('costcenter');
    		$this->view_data['costcenters'] = $this->basemodel->find();
    		
    		$this->view_data['suppliers'] = $this->companiesmodel->find( array('archived' => 0, 'supplier' => 1), null, null, 'company_name');
    		
    		if (!$companyid) {
    			$this->view_data['companies'] = $this->companiesmodel->find( array() );
    			$this->view_data['company_select'] = true;
    		} else {
    			$this->view_data['company_select'] = false;
    		}
    		
	    	$this->layout->buildPage('jobs/add', $this->view_data);
    	}
    }
    
    public function view($jobid, $company_name = false) {
		$this->load->model('jobsmodel');
    	$this->load->model('companiesmodel');
    	$this->load->model('costcentermodel');
    	$this->load->model('contactmodel');
    	$this->load->model('usersmodel');
    	$this->load->model('timesheetmodel');

			$this->view_data['page_js'][] = 'jquery.inplace';
			$this->view_data['page_js'][] = 'companies_inplace';
		
		$job = $this->jobsmodel->retrieve_by_name($jobid, $company_name);
		if (!$job && intval($jobid)) $job = $this->jobsmodel->retrieve_by_pkey($jobid);
    	
    	if (!$this->canAccess($jobid)) redirect('');

    	$this->view_data['page_js'][] = 'job';
    	
    	$jobid = $job->id;
    	$company = $this->companiesmodel->retrieve_by_pkey($job->companyid);
    	
    	$this->view_data['job'] = $job;
		$this->view_data['company'] = $company;


		//get departments
    	$costcenters = $this->costcentermodel->getCostCentersForJob($job->id);
		//get time logged for departments
		if ($costcenters) {
			foreach($costcenters as $key => $department) {
				$costcenters[$key]->timespent = $this->timesheetmodel->getTimeSpent($job->id, $department->id);
			}
		}
		$this->view_data['costcenters'] = $costcenters;

    	
    	//get the cost centers not used already.
    	$unusedcenters = $this->costcentermodel->getUnusedCostCentersForJob($job->id);
		$this->view_data['unusedcenters'] = $unusedcenters;


    	//get all contacts for this client
    	$contacts = $this->contactmodel->getContactsForCompany($company->id);
    	$contact_select = '';
    	if ($contacts) {
    		foreach($contacts as $key => $contact) {
    			$contact_select .= $contact->firstname. ' '.$contact->surname.":".$contact->id;
	    		if ($key + 1 < count($contacts)) $contact_select .= ',';
    		}
    	}
    	$this->view_data['contacts'] = $contacts;
    	$this->view_data['contact_select'] = $contact_select;
		
		$this->calcJobTime($job->id);
		
		if ($company->client) $this->view_data['maintab'] = 'Clients';
		else if ($company->prospect) $this->view_data['maintab'] = 'Prospects';
		else if ($company->supplier) $this->view_data['maintab'] = 'Suppliers';
		
		/*todo: tidy this shit up */
		
		$this->load->model('companiesmodel');
		$this->load->model('jobsmodel');
		$this->load->model('costcentermodel');
		$this->load->model('activitymodel');
		$this->load->model('usersmodel');

		$this->view_data['page_js'][] = 'userassign';
		
		$job = $this->jobsmodel->retrieve_by_name($jobid, $company_name);
		if (!$job && intval($jobid)) $job = $this->jobsmodel->retrieve_by_pkey($jobid);

		if ( !$job || !$this->canAccess($job->id)) redirect('');	

		$company = $this->companiesmodel->retrieve_by_pkey($job->companyid);

		$departments = $this->costcentermodel->getCostCentersForJob($job->id);
		
		$hasTasks = false;
		
		if ($departments) {		
			foreach($departments as $key => $department) {
				$tasks = $this->costcentermodel->getActivitiesForCostCenter($department->id);

				$departments[$key]->tasks = $tasks;
				if ($tasks) $hasTasks = true;
			}
		}


		$assigned_users = $this->jobsmodel->getAssignedUsers($job->id);
		
		if ($assigned_users) {
		
			foreach ($assigned_users as $key => $user ) {
				if ($user->job_costcenterid > 0) $assigned_users[$key]->department = $this->costcentermodel->retrieve_by_pkey($user->job_costcenterid);
				else $assigned_users[$key]->department = false;
				
				if ($user->activityid > 0) $assigned_users[$key]->task = $this->activitymodel->retrieve_by_pkey($user->activityid);
				else $assigned_users[$key]->task = false;
				
			}
		
		}
		
		$this->view_data['job'] = $job;
		$this->view_data['company'] = $company;
		$this->view_data['departments'] = $departments;
		
		$this->view_data['assigned_users'] = $assigned_users;
		$this->view_data['users'] = $this->usersmodel->find( array('active' => 1, 'deleted' => 0, 'profiletype' => '!client'), false, false, 'lastname ASC') ;
		$this->view_data['hastasks'] = $hasTasks;
		
		$this->calcJobTime($job->id);
		
		
    	$this->layout->buildPage('jobs/view', $this->view_data);
    }
    
    public function deleteTimesheet() {
    	$timesheetid = $this->input->post('timesheetid');
    	
    	if ($timesheetid) {
    	
    		$timesheetidparts = explode('-', $timesheetid);
    		$id = $timesheetidparts[1];
    	
    		$this->load->model('timesheetmodel');
    	
    		$this->timesheetmodel->delete_by_pkey($id);
    	
    		echo $id;
    	}
    	else echo false;
    	die();
    }
    
    public function schedule($jobid, $company_name = false) {
    	$this->load->model('costcentermodel');
    	$this->load->model('jobsmodel');
    	$this->load->model('companiesmodel');
    	
		$job = $this->jobsmodel->retrieve_by_name($jobid, $company_name);
		if (!$job && intval($jobid)) $job = $this->jobsmodel->retrieve_by_pkey($jobid);

    	if (!$job || !$this->canAccess($jobid)) redirect('');

    	$company = $this->companiesmodel->retrieve_by_pkey($job->companyid);
    	
    	
    	$costcenters = $this->costcentermodel->getCostCentersForJob($job->id);
    	
    	$firstdate = null;
    	$lastdate = null;
    	
    	if ($costcenters) {
    	
			foreach($costcenters as $key => $center) {
				$tasks = $this->costcentermodel->getActivitiesForCostCenter($center->id);
				
				if ($center->startdate) {
					if ($firstdate == null || $firstdate > strtotime($center->startdate)) $firstdate = strtotime($center->startdate);
					if ($lastdate == null || $lastdate < strtotime($center->startdate)) $lastdate = strtotime($center->startdate);
				}
				
				if ($center->enddate) {
					if ($firstdate == null || $firstdate > strtotime($center->enddate)) $firstdate = strtotime($center->enddate);
					if ($lastdate == null || $lastdate < strtotime($center->enddate)) $lastdate = strtotime($center->enddate);
				}
				
				$costcenters[$key]->tasks = $tasks;
				
				if ($tasks) {
					foreach($tasks as $task) {
						if ($task->startdate) {
							if ($firstdate == null || $firstdate > strtotime($task->startdate)) $firstdate = strtotime($task->startdate);
							if ($lastdate == null || $lastdate < strtotime($task->startdate)) $lastdate = strtotime($task->startdate);
						}
						if ($task->enddate) {
							if ($firstdate == null || $firstdate > strtotime($task->enddate)) $firstdate = strtotime($task->enddate);
							if ($lastdate == null || $lastdate < strtotime($task->enddate)) $lastdate = strtotime($task->enddate);
						}
					}
				}
			} 
    	
    	}
    	
    	if ($firstdate && $lastdate) {
    	
			$this->view_data['departments'] = $costcenters;
			$this->view_data['firstdate'] = $firstdate;
			$this->view_data['lastdate'] = $lastdate;
			
			$daycount = round( abs( $lastdate - $firstdate ) / 86400 );
			
			$this->view_data['daycount'] = $daycount;
			
			$dateheaders = '';
			
			for($x = 0; $x <= $daycount; $x ++) {
				$thisday = $firstdate + ($x * 86400);
				$tdstr = date('dmY', $thisday);
				$todaystr = date('dmY');
				
				$dateheaders .= '<th id="date-'.date('dmY', $thisday ).'" class="'.(( $tdstr == $todaystr ) ? ' today' : '' ).'">'.date('d/m', $firstdate + ($x * 86400) ).'</th>';
			}
			
			$firstcols = array();
			$rows = array();
			
			foreach ($costcenters as $key => $center) {
				
				if ($center->startdate && $center->enddate) {
					$startpadding = round( abs( strtotime($center->startdate) - $firstdate ) / 86400 );
					$length = round( abs( strtotime($center->enddate) - strtotime($center->startdate) ) / 86400 );
					$endpadding = round( abs( $lastdate - strtotime($center->enddate) ) / 86400 );
					
					$length++;
				} elseif ($center->startdate) {
					$startpadding = round( abs( strtotime($center->startdate) - $firstdate ) / 86400 );
					$length = 1;
					$endpadding = round( abs( $lastdate - strtotime($center->startdate) ) / 86400 );
				} elseif ($center->enddate) {
					$startpadding = round( abs( strtotime($center->enddate) - $firstdate ) / 86400 );
					$length = 1;
					$endpadding = round( abs( $lastdate - strtotime($center->enddate) ) / 86400 );
				} else {
					$startpadding = false;
					$length = false;
					$endpadding = false;
				}
				
				$firstcol = '<th class="dept">'.$center->centertitle.'</th>';
				$row = '<tr class="timeline-dept">';
				
				
				if ($startpadding) $row .= '<td free="start" colspan="'.$startpadding.'">&nbsp;</td>';
				if ($length) $row .= '<td class="busy-dept" colspan="'.$length.'">&nbsp;</td>';
				if ($endpadding) $row .= '<td class="free" colspan="'.$endpadding.'">&nbsp;</td>';
				$row .= '</tr>';
				
				$firstcols[] = $firstcol;
				$rows[] = $row;
				
				
				
				if ($center->tasks) {
					foreach($center->tasks as $task) {
	
						$startpadding = round( abs( strtotime($task->startdate) - $firstdate ) / 86400 );
						$length = round( abs( strtotime($task->enddate) - strtotime($task->startdate) ) / 86400 );
						$endpadding = round( abs( $lastdate - strtotime($task->enddate) ) / 86400 );
						
						$length++;
						
						$firstcol = '<th class="task">'.$task->activity_title.'</th>';
						
						
						
						$row = '<tr class="timeline-task '.(($task->deadline) ? ' deadline' : '' ).(($task->milestone) ? ' milestone' : '').'">';
						if ($startpadding) $row .= '<td class="free" colspan="'.$startpadding.'">&nbsp;</td>';
						$row .= '<td class="busy-task" colspan="'.$length.'">&nbsp;</td>';
						if ($endpadding) $row .= '<td class="free" colspan="'.$endpadding.'">&nbsp;</td>';
						$row .= '</tr>';
						
						$firstcols[] = $firstcol;
						$rows[] = $row;
					}
				}
			}
			
			
			
			$this->view_data['dateheaders'] = $dateheaders;
			$this->view_data['firstcols'] = $firstcols;
			$this->view_data['rows'] = $rows;
			
			$this->view_data['schedule_data'] = true;
		} else {
			$this->view_data['schedule_data'] = false;
		}
		
		    	
		$this->view_data['company'] = $company;
    	$this->view_data['job'] = $job;
    	$this->calcJobTime($job->id);
    	
    	$this->layout->buildPage('jobs/schedule', $this->view_data);
    }
    
    public function generateInvoice($jobid, $company_name = false) {
    	$this->load->model('jobsmodel');
		$this->load->model('invoicemodel');
		$this->load->library('validation');

		$job = $this->jobsmodel->retrieve_by_name($jobid, $company_name);
		if (!$job && intval($jobid)) $job = $this->jobsmodel->retrieve_by_pkey($jobid);

		if (!$job || !$this->canAccess($job->id)) echo 123; //redirect('');

		//set up validation
		$rules['invoice_title']	= "trim|required";
		$rules['invoice_description'] = "trim";
		$rules['invoice_duedate'] = "trim|required";
		$rules['invoice_reference']	= "trim";
		$rules['address']	= "required";
		$rules['attentionof']	= "required";
		
		$this->validation->set_rules($rules);

		$fields['invoice_title'] = 'Title';
		$fields['invoice_description'] = 'Description';
		$fields['invoice_duedate'] = 'Due Date';
		$fields['invoice_reference'] = 'Reference';
		$fields['attentionof'] = 'Contact';
		$fields['address'] = 'Address';
	
		$this->validation->set_fields($fields);
		
		//set up view defaults
		$departmentlines = false;
		$costlines = false;
		$extraslines = false;
		
		//check if form was submitted
    	$submit = $this->input->post('submit', false);
    	
    	$savedata = false;
    	
    	if ($submit) {
    	    	
			$invoice = null;
			
			$invoice->invoicetitle = $this->input->post('invoice_title', true);
			$invoice->description = $this->input->post('invoice_description', true);
			
			if ($this->input->post('invoice_duedate', TRUE)) {
				$dateParts = explode('/', $this->input->post('invoice_duedate', TRUE));
				if ($dateParts && count($dateParts) == 3) $invoice->duedate = date('Y-m-d', mktime(0, 0, 0, $dateParts[1], $dateParts[0], $dateParts[2]) );
			}
			
			$invoice->reference = $this->input->post('invoice_reference', true);
			$invoice->jobid = $this->input->post('jobid', true);
			$invoice->companyid = $this->input->post('companyid', true);
			
			$invoice->datecreated = date('Y-m-d H:i:s');
			$invoice->creatorid = $this->authentication->getUserId();
			
			$address = $this->input->post('address', true);
			if (is_numeric($address)) $invoice->addressid = $address;
			else $invoice->address_text = $address;
			
			$attentionof = $this->input->post('attentionof', true);
			if (is_numeric($address)) $invoice->attentionofid = $attentionof;
			else $invoice->attentionof_text = $attentionof;

			$invoicelines = array();
			
			//process departmental costs

			$departments = $this->input->post('includedepartment', true);
			$departmentlines = array();
			
			if ($departments) {
				$thisline = null;
				
				foreach ($departments as $departmentkey) {
				
					$thisline->department = $this->input->post($departmentkey.'_department', true);
					$thisline->departmentid = $this->input->post($departmentkey.'_id', true);
					$thisline->description = $this->input->post($departmentkey.'_description', true);
					$thisline->cost = $this->input->post($departmentkey.'_cost', true);
					
					$invoicelines[] = clone $thisline;
					$departmentlines[$departmentkey] = clone $thisline;
				}
				
			}
			
			//process external costs
			
			$costs = $this->input->post('includecost', true);
			$costlines = array();
			
			if ($costs) {
				$thisline = null;
				
				foreach ($costs as $costkey) {
					$thisline->department = $this->input->post($costkey.'_department', true);
					$thisline->costid = $this->input->post($costkey.'_id', true);
					$thisline->description = $this->input->post($costkey.'_description', true);
					$thisline->cost = $this->input->post($costkey.'_cost', true);
					
					$invoicelines[] = clone $thisline;
					$costlines[$costkey] = clone $thisline;
				}
				
			}
			
			//process additional costs
			
			$extras = $this->input->post('includeextras', true);
			$extraslines = array();
			
			if ($extras) {
				$thisline = null;
				
				foreach ($extras as $extraskey) {
					$thisline->department = $this->input->post($extraskey.'_department', true);
					$thisline->description = $this->input->post($extraskey.'_description', true);
					$thisline->cost = $this->input->post($extraskey.'_cost', true);
					
					$invoicelines[] = clone $thisline;
					$extraslines[$extraskey] = clone $thisline;
				}
			}
		
			if ($this->validation->run()) $savedata = true;
			else {
				//store lines in view for editing
				$this->view_data['departmentlines'] = $departmentlines;
				$this->view_data['costlines'] = $costlines;
				$this->view_data['extraslines'] = $extraslines;
			}
		
		}
		
		if ( $savedata ) {
		
			$invoiceid = $this->invoicemodel->add($invoice);
			
			if ($invoiceid) {
				foreach ($invoicelines as $line) {
					$line->invoiceid = $invoiceid;
					$this->invoicemodel->addLine($line);
				}
			}
			
			redirect('jobs/viewinvoice/'.$invoiceid);
    	} else {
			$this->load->model('costcentermodel');
			$this->load->model('timesheetmodel');
			$this->load->model('costmodel');
			$this->load->model('contactmodel');
			$this->load->model('jobsmodel');
			$this->load->model('companiesmodel');
			
			$this->view_data['page_js'][] = 'invoice';
			
			$company = $this->companiesmodel->retrieve_by_pkey($job->companyid);
			
			$costcenters = $this->costcentermodel->getCostCentersForJob($job->id);
		
			if ($costcenters) {
		
				foreach ($costcenters as $key => $department) {
		
					$costcenters[$key]->actualhours = $this->timesheetmodel->getTimeSpent($job->id, $department->id, 0);
					$costcenters[$key]->previouslybilled = $this->invoicemodel->getPreviouslyBilled($company->id, $job->id, $department->id);
				}
			
			}
			
			$costs = $this->costmodel->getCostsFor( $job->id );
			
			if ($costs) {
		
				foreach ($costs as $key => $cost) {
		
					$costs[$key]->previouslybilled = $this->invoicemodel->getPreviouslyBilled($company->id, $job->id, false, $cost->id);
				}
			
			}
			
			$unallocatedhours = $this->timesheetmodel->getTimeSpent($job->id, 0, 0);
			$unbillablehours = $this->timesheetmodel->getTimeSpent($job->id, false, 1);
			
			$otherinvoices = $this->invoicemodel->getOtherInvoices($company->id, $job->id);
			
			$contacts = $this->contactmodel->getContactsForCompany($company->id);
			$addresses = $this->companiesmodel->getAddresses($company->id);
			
			//data for repopulation of form
			$this->view_data['departmentlines'] = $departmentlines;
			$this->view_data['costlines'] = $costlines;
			$this->view_data['extraslines'] = $extraslines;
			
			//view data
			$this->view_data['costs'] = $costs;
			$this->view_data['costcenters'] = $costcenters;
			$this->view_data['unallocatedhours'] = $unallocatedhours;
			$this->view_data['unbillablehours'] = $unbillablehours;
			$this->view_data['job'] = $job;
			$this->view_data['company'] = $company;
			$this->view_data['otherinvoices'] = $otherinvoices;
			
			$this->view_data['contacts'] = $contacts;
			$this->view_data['addresses'] = $addresses;
			
			$this->calcJobTime($job->id);
			
			$this->layout->buildPage('jobs/invoice', $this->view_data);
		}
    }
    
    public function viewinvoice($invoiceid) {
    	$this->load->model('invoicemodel');
    	$this->load->model('jobsmodel');
		$this->load->model('companiesmodel');
		$this->load->model('contactmodel');
		
    	$invoice = $this->invoicemodel->retrieve_by_pkey($invoiceid);
    	
    	if (!$invoice) redirect('');
    	
    	$this->view_data['page_js'][] = 'jquery.inplace';
		$this->view_data['page_js'][] = 'companies_inplace';

    	$company = $this->companiesmodel->retrieve_by_pkey($invoice->companyid);
		$job = $this->jobsmodel->retrieve_by_pkey($invoice->jobid);
		
		if (!$this->canAccess($job->id)) redirect('');
    	
    	$invoice->lines = $this->invoicemodel->getLines($invoiceid);
    	
    	if ($invoice->attentionofid) $invoice->attentionof = $this->contactmodel->retrieve_by_pkey($invoice->attentionofid);
    	if ($invoice->addressid) $invoice->address = $this->companiesmodel->getAddresses($company->id, $invoice->addressid);
    	
    	$otherinvoices = $this->invoicemodel->getOtherInvoices($company->id, $job->id, $invoice->id);
    	
    	$this->view_data['invoice'] = $invoice;
    	$this->view_data['company'] = $company;
    	$this->view_data['job'] = $job;
    	$this->view_data['otherinvoices'] = $otherinvoices;
    	
    	$this->calcJobTime($job->id);
    	
    	$this->layout->buildPage('jobs/viewinvoice', $this->view_data);
    }
    
	public function markInvoicePaid($invoiceid) {
		$this->load->model('invoicemodel');
		
		$this->invoicemodel->markPaid($invoiceid);
		
		redirect('jobs/viewinvoice/'.$invoiceid);
	}
	
	public function markInvoiceUnpaid($invoiceid) {
		$this->load->model('invoicemodel');
		
		$this->invoicemodel->markUnpaid($invoiceid);
		
		redirect('jobs/viewinvoice/'.$invoiceid);
	}

	public function markInvoiceProcessed($invoiceid) {
		$this->load->model('invoicemodel');
		
		$this->invoicemodel->markProcessed($invoiceid);
		
		redirect('jobs/viewinvoice/'.$invoiceid);
	}
	
	public function markInvoiceUnprocessed($invoiceid) {
		$this->load->model('invoicemodel');
		
		$this->invoicemodel->markUnprocessed($invoiceid);
		
		redirect('jobs/viewinvoice/'.$invoiceid);
	}
	
	public function markInvoiceCancelled($invoiceid) {
		$this->load->model('invoicemodel');
		
		$this->invoicemodel->markCancelled($invoiceid);
		
		redirect('jobs/viewinvoice/'.$invoiceid);
	}
    
    
    public function addCostCenter() {
    	$this->load->model('costcentermodel');
    	$this->load->model('jobsmodel');
    	$this->load->model('timesheetmodel');
    	
    	$data->jobid = $this->input->post('jobid');
    	$data->costcenterid = $this->input->post('costcenterid');
    	
    	if ($this->input->post('startdate', TRUE)) {
	    	$dateParts = explode('/', $this->input->post('startdate', TRUE));
			$data->startdate	= date('Y-m-d', mktime(0, 0, 0, $dateParts[1], $dateParts[0], $dateParts[2]) );
    	}

		if ($this->input->post('enddate', TRUE)) {
	    	$dateParts = explode('/', $this->input->post('enddate', TRUE));
			$data->enddate	= date('Y-m-d', mktime(0, 0, 0, $dateParts[1], $dateParts[0], $dateParts[2]) );
    	}
    	
    	$data->notes = $this->input->post('notes');
    	
    	
    	$data->hourlyrate = $this->input->post('hourlyrate');
    	if (!$data->hourlyrate) {
    		$this->load->model('costcentermodel');
    		$cc = $this->costcentermodel->getDepartment($data->costcenterid);
    		
    		$data->hourlyrate = $cc->hourlyrate;
    	}
    	
    	$data->allocatedhours = $this->input->post('allocatedhours');
 
		$data->datecreated = date('Y-m-d H:i:s');
		$data->creatorid = $this->authentication->getUserId();


    	$job_costcenterid = $this->costcentermodel->add($data);
    	
    	//store new department in timesheets table
    	
		$ccData = $this->costcentermodel->retrieve_by_pkey($job_costcenterid);
    	$jobData = $this->jobsmodel->retrieve_by_pkey($ccData->jobid);
    	
    	//check who is on autoassign for this department
    	$this->costcentermodel->autoAssign($jobData->companyid, $ccData->jobid, $job_costcenterid, $data->costcenterid);
    	
    	$assignedUsers = $this->costcentermodel->getAutoAssign($jobData->companyid, $ccData->jobid, $job_costcenterid, $data->costcenterid);
    	
    	if ($assignedUsers) {
			$this->load->library('notifications');
			
			foreach ($assignedUsers as $user) {
				$this->notifications->assignmentNotification($user->id, $jobData->companyid, $ccData->jobid, $job_costcenterid);
			}
    	}
    	$this->db_session->set_flashdata('flashmessage', 'Added the new Department: '.$ccData->centertitle);
    	
    	
    	redirect('jobs/view/'.$data->jobid);
    }
    
    public function deleteDepartment($departmentid = 0) {
    	$this->load->model('costcentermodel');
    	
    	if ($departmentid) {
			$department = $this->costcentermodel->retrieve_by_pkey($departmentid);

    		$this->costcentermodel->pseudoDelete($department->id);
    	
			$undo_url = site_url('jobs/undeleteDepartment/'.$department->id);
			
			$this->db_session->set_flashdata('flashmessage', $department->centertitle.' was deleted. <a href="'.$undo_url.'">Undo</a>');
		
		}
		redirect('jobs/view/'.$department->jobid);
    }
    
	public function undeleteDepartment($departmentid = 0) {
    	$this->load->model('costcentermodel');
    	
    	if ($departmentid) {
			$department = $this->costcentermodel->retrieve_by_pkey($departmentid);

    		$this->costcentermodel->pseudoUndelete($department->id);
    	
			$undo_url = site_url('jobs/deleteDepartment/'.$department->id);
			
			$this->db_session->set_flashdata('flashmessage', $department->centertitle.' was undeleted. <a href="'.$undo_url.'">Redo</a>');
		
		}
		redirect('jobs/view/'.$department->jobid);
    }
    
    public function addActivity() {
    	$this->load->model('activitymodel');
    	$this->load->model('timesheetmodel');
    	$this->load->model('jobsmodel');
    	
    	$jobid = $this->input->post('jobid');
    	
    	if ($jobid) {
    	
    		$job = $this->jobsmodel->retrieve_by_pkey($jobid);
    	
			$data->jobid = $job->id;
			$data->companyid = $job->companyid;
			$data->job_centerid = $this->input->post('department');
			$data->activity_title = $this->input->post('activity_title');
			
			if ($this->input->post('startdate', TRUE)) {
				$dateParts = explode('/', $this->input->post('startdate', TRUE));
				if ($dateParts) $data->startdate	= date('Y-m-d', mktime(0, 0, 0, $dateParts[1], $dateParts[0], $dateParts[2]) );
			}
			
			if ($this->input->post('enddate', TRUE)) {
				$dateParts = explode('/', $this->input->post('enddate', TRUE));
				if ($dateParts) $data->enddate = date('Y-m-d', mktime(0, 0, 0, $dateParts[1], $dateParts[0], $dateParts[2]) );
			}
			
			if ( $this->input->post('allocatedhours') ) $data->allocatedhours = $this->input->post('allocatedhours');
			
			$data->completion = 0;
			$data->activity_notes = $this->input->post('activity_notes');
	
			$updatetype = $this->input->post('updatetype');
	
			if ( $updatetype == 'deadline' ) $data->deadline = 1;
			else if ( $updatetype == 'milestone' ) $data->milestone = 1;
	
			$data->datecreated = date('Y-m-d H:i:s');
			$data->creatorid = $this->authentication->getUserId();
			
			$activityid = $this->activitymodel->add($data);
			
			$this->db_session->set_flashdata('flashmessage', 'Added the new Task: '.$data->activity_title);
    	}
    	
    	redirect('jobs/milestones/'.$data->jobid);
    }
    
    public function deleteActivity($activityid = 0) {
    	$this->load->model('activitymodel');
    	
    	if ($activityid) {
			$activity = $this->activitymodel->retrieve_by_pkey($activityid);

    		$this->activitymodel->pseudoDelete($activity->id);
    	
			$undo_url = site_url('jobs/undeleteActivity/'.$activity->id);
			
			$this->db_session->set_flashdata('flashmessage', $activity->activity_title.' was deleted. <a href="'.$undo_url.'">Undo</a>');
		
		}
		redirect('jobs/milestones/'.$activity->jobid);
    }
    
    public function undeleteActivity($activityid = 0) {
    	$this->load->model('activitymodel');
    	
    	if ($activityid) {
			$activity = $this->activitymodel->retrieve_by_pkey($activityid);

    		$this->activitymodel->pseudoUndelete($activity->id);
    	
			$undo_url = site_url('jobs/deleteActivity/'.$activity->id);
			
			$this->db_session->set_flashdata('flashmessage', $activity->activity_title.' was undeleted. <a href="'.$undo_url.'">Redo</a>');
		
		}
		redirect('jobs/milestones/'.$activity->jobid);
    }
    
    public function addCost() {
    	$this->load->model('costmodel');
    	$this->load->model('jobsmodel');
    	$this->load->model('timesheetmodel');
    	
    	$data->jobid = $this->input->post('jobid');
    	$data->cost_title = $this->input->post('cost_title');
		$data->quote_ref = $this->input->post('quote_ref');
		$data->supplierid = $this->input->post('supplierid');

    	$data->incoming_cost = $this->input->post('incoming_cost');
    	$data->outgoing_cost = $this->input->post('outgoing_cost');
		$data->cost_description = $this->input->post('cost_description');
		
		$data->datecreated = date('Y-m-d H:i:s');
		$data->creatorid = $this->authentication->getUserId();
    	
    	$costid = $this->costmodel->add($data);
    	
    	$this->db_session->set_flashdata('flashmessage', 'Added the new Cost: '.$data->cost_title);
    	
    	redirect('jobs/costs/'.$data->jobid);
    }
    
    public function deleteCost($costid = 0) {
    	$this->load->model('costmodel');
    	
    	if ($costid) {
			$cost = $this->costmodel->retrieve_by_pkey($costid);

    		$this->costmodel->pseudoDelete($cost->id);
    	
			$undo_url = site_url('jobs/undeleteCost/'.$cost->id);
			
			$this->db_session->set_flashdata('flashmessage', $cost->cost_title.' was deleted. <a href="'.$undo_url.'">Undo</a>');
		
		}
		redirect('jobs/costs/'.$cost->jobid);
    }
    
	public function undeleteCost($costid = 0) {
    	$this->load->model('costmodel');
    	
    	if ($costid) {
			$cost = $this->costmodel->retrieve_by_pkey($costid);

    		$this->costmodel->pseudoUndelete($cost->id);
    	
			$undo_url = site_url('jobs/deleteCost/'.$cost->id);
			
			$this->db_session->set_flashdata('flashmessage', $cost->cost_title.' was undeleted. <a href="'.$undo_url.'">Redo</a>');
		
		}
		redirect('jobs/costs/'.$cost->jobid);
    }
    
    
    function chart_data($values, $axis = 0) {
		$maxValue = max($values);
		
		// A list of encoding characters to help later, as per Google's example
		$simpleEncoding = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
		
		$chartData = "s:";
		  for ($i = 0; $i < count($values); $i++) {
			$currentValue = $values[$i];
		
			if ($currentValue > -1) {
			$chartData.=substr($simpleEncoding,61*($currentValue/$maxValue),1);
			}
			  else {
			  $chartData.='_';
			  }
		  }
		
		// Return the chart data - and let the Y axis to show the maximum value
		return $chartData."&chxt=y&chxl=".$axis.":|0|".$maxValue;
	}
    
    private function calcJobTime($jobid) {
    	$this->load->model('timesheetmodel');
    	$this->load->model('jobsmodel');
    	
    	$job = $this->jobsmodel->retrieve_by_pkey($jobid);
    	
    	$allocatedtime = $this->jobsmodel->getAllocatedTimeForJob($job->id);
    	$totaltime = $this->timesheetmodel->getTimeSpent($job->id);
		$usertime = $this->timesheetmodel->getTimeSpent($job->id, false, 0, $this->authentication->getUserId() );
		
		$this->view_data['allocatedtime'] = $allocatedtime;
		$this->view_data['totaltime'] = $totaltime;
		$this->view_data['usertime'] = $usertime;
    }
    
    public function showUpdates($jobid, $company_name = false) {
    	$this->load->model('timesheetmodel');
    	$this->load->model('companiesmodel');
    	$this->load->model('jobsmodel');
    	$this->load->model('costcentermodel');
    	$this->load->model('activitymodel');
    	$this->load->model('filesmodel');

		$job = $this->jobsmodel->retrieve_by_name($jobid, $company_name);
		if (!$job && intval($jobid)) $job = $this->jobsmodel->retrieve_by_pkey($jobid);

    	if ( !$job || !$this->canAccess($job->id)) redirect('');
		
    	$this->view_data['page_js'][] = 'jquery.inplace';
		$this->view_data['page_js'][] = 'companies_inplace';
    	
    	
    	$this->view_data['page_js'][] = 'timesheet';
    	
    	//get update for this item
    	$updates = $this->timesheetmodel->whatsGoingOn($job->id, $this->authentication->getUserId(), $from = false, $to = false, $assignedonly = false, $companyid = false, $this->permissions->publiccommentsonly);
    	
    	if ($updates) {    	
			foreach($updates as $key => $update) {
				$updates[$key]->files = $this->filesmodel->find( array('jobid' => $job->id, 'timesheetid' => $update->id), null, null, 'title ASC' );
			}
    	}
    	
    	$this->view_data['updates'] = $updates;
    	$this->view_data['candelete'] = true;
    	$updatelist = $this->load->view('epicentr/content/timesheets/whatsgoingon', $this->view_data, true);
		$this->view_data['updatelist'] = $updatelist;

    	
		$filefilter = array('jobid' => $job->id, 'deleted' => 0);
		
		if ($this->authentication->getProfileType() == 'client') $filefilter['public'] = 1;
		
		$jobfiles = $this->filesmodel->find( $filefilter, null, null, 'title ASC');
    	
    	
    	
		$company = $this->companiesmodel->retrieve_by_pkey($job->companyid);
		
		$departments = $this->costcentermodel->getCostCentersForJob($job->id);
		
		$hasTasks = false;
		
		if ($departments) {		
			foreach($departments as $key => $department) {
				$tasks = $this->costcentermodel->getActivitiesForCostCenter($department->id);

				$departments[$key]->tasks = $tasks;
				if ($tasks) $hasTasks = true;
			}
		}
		
		$jobtasks = $this->costcentermodel->getActivitiesForJob($job->id, true);
		$this->view_data['jobtasks'] = $jobtasks;
		
		if (!$hasTasks && $jobtasks) $hasTasks = true;
		
		$this->calcJobTime($job->id);
		
		$this->view_data['company'] = $company;
		$this->view_data['job'] = $job;
		$this->view_data['departments'] = $departments;
		$this->view_data['hastasks'] = $hasTasks;
		$this->view_data['jobfiles'] = $jobfiles;
		
		if ($company->client) $this->view_data['maintab'] = 'Clients';
		else if ($company->prospect) $this->view_data['maintab'] = 'Prospects';
		else if ($company->supplier) $this->view_data['maintab'] = 'Suppliers';
		
    	$this->layout->buildPage('jobs/timesheet', $this->view_data);
    }
    
    public function addUpdate() {
    	$this->load->model('jobsmodel');
		$this->load->model('costcentermodel');
    	$this->load->model('timesheetmodel');
    	$this->load->model('activitymodel');
    	
		$jobid = $this->input->post('jobid');
    	
    	$job = $this->jobsmodel->retrieve_by_pkey($jobid);
    	
    	if (!$job) redirect('');
    	
    	$costcenterid = 0;
    	$activityid = 0;
    	
    	$updatefor = $this->input->post('updatefor');
    	
    	switch ($updatefor) {
			case "department":
    			$costcenterid = $this->input->post('department');
    		break;
			case "task":
    			$activityid = $this->input->post('task');
				$task = $this->activitymodel->retrieve_by_pkey($activityid);
				$costcenterid = $task->job_centerid;
    		break;
			case "general":
				//just add to the job
			break;
			default:
				//unknown.
				//get users department
				$mydepartment = $this->authentication->getUserField('costcenterid');
				
				if ( $jobdepartment = $this->costcentermodel->jobHasDepartment($job->id, $mydepartment) ) {
					$costcenterid = $jobdepartment;
				}
				
			break;
    	}
    	
    	$data->companyid = $job->companyid;
    	if ($jobid) $data->jobid = $jobid;
    	if ($costcenterid) $data->job_costcenterid = $costcenterid;
    	if ($activityid) $data->activityid = $activityid;
    	
    	if ($this->input->post('dateapplicable', TRUE)) {
	    	$dateParts = explode('/', $this->input->post('dateapplicable', TRUE));
			$data->dateapplicable	= date('Y-m-d', mktime(0, 0, 0, $dateParts[1], $dateParts[0], $dateParts[2]) );
    	} else $data->dateapplicable = date('Y-m-d');
		
		$hoursworked = $this->input->post('hoursworked');
		$minsworked = $this->input->post('minsworked');
		$minsworkedDecimal = ($minsworked / 60);
		
    	$data->hoursworked = $hoursworked + $minsworkedDecimal;
    	$data->notbillable = $this->input->post('notbillable');
    	$data->notes = $this->input->post('notes');
		$data->notes = str_replace("\n\n\n", "\n\n", $data->notes);

    	$data->public = $this->input->post('public');

    	$data->datecreated = date('Y-m-d H:i:s');
		$data->creatorid = $this->authentication->getUserId();

    	$tsid = $this->timesheetmodel->add((array)$data);
    	
    	$this->attachUpdateFiles($job->id, $tsid, $data->public);
    	
    	$this->load->library('notifications');
		$this->notifications->sendNotification($tsid);
    	
    	$this->db_session->set_flashdata('flashmessage', 'Update Added');
    	
    	$from = $this->input->post('from');
    	
    	if ($from) redirect($from);
		else redirect('jobs/showUpdates/'.$jobid);
    }
    
    private function attachUpdateFiles($jobid, $timesheetid = 0, $public = 0) {
		$this->load->model('jobsmodel');
    	$this->load->model('filesmodel');
    	
		// require_once('Zend/Gdata/Docs.php');
		// require_once('Zend/Gdata/ClientLogin.php');

    	$job = $this->jobsmodel->retrieve_by_pkey($jobid);

		if ($job) {
			
			$count = 0;
			
			$data = array();
			
			$config['upload_path'] = $this->uploadpath;
			$config['allowed_types'] = $this->allowed_file_types;
			
			$this->load->library('upload', $config);
			
			do {
				$fieldname = "fileupload";
				if ($count > 0 ) $fieldname.= $count;
				$count ++;

				$fileUploaded = $this->upload->do_upload($fieldname);
				$uploadData = $this->upload->data();
				
				if ($fileUploaded) {
					$file_data = null;
	
					$file_data->jobid = $job->id;
					if ($timesheetid) $file_data->timesheetid = $timesheetid;
	
					$file_data->title = $uploadData['file_name'];
					$file_data->file_name = $uploadData['file_name'];
					$file_data->file_type = $uploadData['file_type'];
					$file_data->file_path = $uploadData['file_path'];
					$file_data->file_size = $uploadData['file_size'];
					$file_data->public = $public;
					
					$file_data->datecreated = date('Y-m-d H:i:s');
					$file_data->creatorid = $this->authentication->getUserId();
				
					if ( 0 && in_array($file_data->file_type, array('application/msword')) ) {
						//this data needs to be a config setting as well
						//$user = '';
						//$pass = '';
						$service = Zend_Gdata_Docs::AUTH_SERVICE_NAME; // predefined service name for Google Documents

						$httpClient = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
						$gdClient = new Zend_Gdata_Docs($httpClient);
				
						try {							
							$newDocumentEntry = $gdClient->uploadFile($file_data->file_path.$file_data->file_name, '['.$job->job_number.']'.$file_data->title, $file_data->file_type, Zend_Gdata_Docs::DOCUMENTS_LIST_FEED_URI);

							$alternateLink = $newDocumentEntry->getAlternateLink()->getHref();
							$urlcomponents = parse_url($alternateLink);
							$queryparts = explode('=', $urlcomponents['query']);
					
							$file_data->googledocsid = $queryparts[1];
						} catch (Exception $e) {
								echo 'Caught exception: ',  $e->getMessage(), "\n";
						}
					}
				
					$this->filesmodel->add($file_data);
					
				} //else echo $this->upload->display_errors();
			} while ($fileUploaded);
		}
		
		return true;
    }

    public function showAssignedUsers($jobid = false, $company_name = false) {
		$this->load->model('companiesmodel');
		$this->load->model('jobsmodel');
		$this->load->model('costcentermodel');
		$this->load->model('activitymodel');
		$this->load->model('usersmodel');

		$this->view_data['page_js'][] = 'userassign';
		
		$job = $this->jobsmodel->retrieve_by_name($jobid, $company_name);
		if (!$job && intval($jobid)) $job = $this->jobsmodel->retrieve_by_pkey($jobid);

		if ( !$job || !$this->canAccess($job->id)) redirect('');	

		$company = $this->companiesmodel->retrieve_by_pkey($job->companyid);

		$departments = $this->costcentermodel->getCostCentersForJob($job->id);
		
		$hasTasks = false;
		
		if ($departments) {		
			foreach($departments as $key => $department) {
				$tasks = $this->costcentermodel->getActivitiesForCostCenter($department->id);

				$departments[$key]->tasks = $tasks;
				if ($tasks) $hasTasks = true;
			}
		}


		$assigned_users = $this->jobsmodel->getAssignedUsers($job->id);
		
		if ($assigned_users) {
		
			foreach ($assigned_users as $key => $user ) {
				if ($user->job_costcenterid > 0) $assigned_users[$key]->department = $this->costcentermodel->retrieve_by_pkey($user->job_costcenterid);
				else $assigned_users[$key]->department = false;
				
				if ($user->activityid > 0) $assigned_users[$key]->task = $this->activitymodel->retrieve_by_pkey($user->activityid);
				else $assigned_users[$key]->task = false;
				
			}
		
		}
		
		$this->view_data['job'] = $job;
		$this->view_data['company'] = $company;
		$this->view_data['departments'] = $departments;
		
		$this->view_data['assigned_users'] = $assigned_users;
		$this->view_data['users'] = $this->usersmodel->find( array('active' => 1, 'deleted' => 0, 'profiletype' => '!client'), false, false, 'lastname ASC') ;
		$this->view_data['hastasks'] = $hasTasks;
		
		$this->calcJobTime($job->id);
		
		$this->layout->buildPage('users/assignment', $this->view_data);
	}
    
    public function assignUser() {
    	$this->load->model('jobsmodel');
    	$this->load->model('basemodel');
    	$this->basemodel->setModel('assignment');
    	
    	
    	$jobid = $this->input->post('jobid');
    	
    	$assignto = $this->input->post('assignto');
    	
    	if ($jobid) $job = $this->jobsmodel->retrieve_by_pkey($jobid);
    	else $job = false;
    	
    	$users = $this->input->post('userid');
    	
    	if ($assignto == 'department') $departmentid = $this->input->post('department');
    	else if ($assignto == 'task') {
    		$taskid = $this->input->post('task');
    		$this->load->model('activitymodel');
    		
    		$task = $this->activitymodel->retrieve_by_pkey($taskid);
    		
    		$departmentid = $task->job_centerid;
    	}
    	
    	
    	
    	
    	if ($job && $users) {
    	
    		foreach ($users as $key => $user) {
    	
    			$data = null;
    	
				$data->userid = $user;
				$data->jobid = $job->id;
				
				if ($departmentid) $data->job_costcenterid = $departmentid;
				else $data->job_costcenterid = 0;
				
				if ($taskid) $data->activityid = $taskid;
				else $data->activityid = 0;
				
				if (!$this->basemodel->find( (array)$data )) {
					$this->basemodel->add($data);
				
					$this->load->library('notifications');
					$this->notifications->assignmentNotification($data->userid, $job->companyid, $job->id, $data->job_costcenterid, $data->activityid);
				}
			
			}
		
		}
    	
    	redirect('jobs/view/'.$job->id);
    }
    
    public function unassignUser($userid, $jobid,  $costcenterid = 0, $activityid = 0) {
    	$this->load->model('basemodel');
    	$this->basemodel->setModel('assignment');
    	
    	$data = null;
    	
    	$data->userid = $userid;
    	$data->jobid = $jobid;
    	$data->job_costcenterid = $costcenterid;
    	$data->activityid = $activityid;
    	
    	$this->basemodel->delete_where((array)$data);
    	
    	redirect('jobs/showAssignedUsers/'.$jobid);
    }
    
    public function changeStatus($jobid = 0) {
    	$this->load->model('jobsmodel');

		$message = '';
    	
    	$formjobid = $this->input->post('jobid');
    	
		$job = $this->jobsmodel->retrieve_by_pkey($formjobid);
    	
    	$data = null;
		if ($job) {

			if ($this->input->post('completed') == 1) {
				$data->job_status = 'complete';
				$message = 'This job has been marked as completed.';	
			}
			
			if ($this->input->post('proposed') == 1) {
				$data->job_status = 'proposed';
				$message = 'This job has been marked as proposed.';	
			}
	
			if ($this->input->post('live') == 1) {
				$data->job_status = 'live';
				$message = 'This job has been made live.';	
			}
	
			if ($this->input->post('cancelled') == 1) {
				$data->cancelled = 1;
				$message = 'This job has been cancelled.';
			}
			
			if ($this->input->post('reinstate') == 1) {
				$data->cancelled = 0;
				$message = 'This job has been reinstated.';	
			}
			
			if ($this->input->post('archive') == 1) {
				$data->archived = 1;
				$message = 'This job has been archived.';	
			}

			if ($this->input->post('unarchive') == 1) {
				$data->archived = 0;
				$message = 'This job has been removed from the archive.';	
			}

			$this->jobsmodel->modify($jobid, $data);

		}

		$this->db_session->set_flashdata('flashmessage', $message);
    		
    	redirect('jobs/view/'.$jobid, 'location');
    }
    
    
    private function _get_job_values($action = null) {
		$data = null;    	
		$data->job_title = $this->input->post('job_title', true);
    	$data->job_number = $this->input->post('job_number', true);
    	$data->job_notes = $this->input->post('job_notes', true);
		$data->job_status =  $this->input->post('job_status', true);
    	
   		if ( $action == 'add') {
			$data->datecreated = date('Y-m-d H:i:s');
			$data->creatorid = $this->authentication->getUserId();
		} else {
			$data->dateupdated = date('Y-m-d H:i:s');
			$data->updaterid = $this->authentication->getUserId();
		}
		
		return $data;
    }

    private function _getCosts() {
		$cost_titles = $this->input->post('cost_title', false);
		$quote_refs = $this->input->post('quote_ref', false);
		$supplierids = $this->input->post('supplierid', false);
		$incoming_costs = $this->input->post('incoming_cost', false);
		$outgoing_costs = $this->input->post('outgoing_cost', false);
		$descriptions = $this->input->post('description', false);
		
		$costs = array();
		
		foreach ($cost_titles as $key => $cost) {
			$costs[$key]->cost_title = $cost_titles[$key];
			$costs[$key]->quote_ref = $quote_refs[$key];
			$costs[$key]->supplierid = $supplierids[$key];
			$costs[$key]->incoming_cost = $incoming_costs[$key];
			$costs[$key]->outgoing_cost = $outgoing_costs[$key];
			$costs[$key]->cost_description = $descriptions[$key];
			$costs[$key]->datecreated = date('Y-m-d H:i:s');
			$costs[$key]->creatorid = $this->authentication->getUserId();
		}
		
		return $costs;
    }
    
	private function _getCostCenters() {
		$costcenterids = $this->input->post('costcenterid', false);
		$startdates = $this->input->post('start_date', false);
		$enddates = $this->input->post('end_date', false);
		$allocatedhours = $this->input->post('allocatedhours', false);
		
		$costcenter = array();
		
		foreach ($costcenterids as $key => $cost) {
			$costcenter[$key]->costcenterid = $costcenterids[$key];

			if (strlen($startdates[$key]) ) {
				$dateParts = explode('/', $startdates[$key]);
				$costcenter[$key]->startdate	= date('Y-m-d', mktime(0, 0, 0, $dateParts[1], $dateParts[0], $dateParts[2]) );
			} else $costcenter[$key]->startdate = "";
			
			if (strlen($enddates[$key]) ) {
				$dateParts = explode('/', $enddates[$key]);
				$costcenter[$key]->enddate	= date('Y-m-d', mktime(0, 0, 0, $dateParts[1], $dateParts[0], $dateParts[2]) );
			} else $costcenter[$key]->enddate = "";
			
			$costcenter[$key]->allocatedhours = $allocatedhours[$key];
			$costcenter[$key]->datecreated = date('Y-m-d H:i:s');
			$costcenter[$key]->creatorid = $this->authentication->getUserId();
		}
		
		return $costcenter;
    }

}
/*
ALTER TABLE `job` ADD `contact2id` int(11) DEFAULT NULL  AFTER `contactid`;
ALTER TABLE `job` ADD `ponumber` varchar(50) DEFAULT NULL  AFTER `contact2id`;*/

?>